package com.video.dao.chat;

import com.video.model.ChatMessage;
import com.video.utils.StringUtils;
import com.video.utils.constant.UrlConstant;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public abstract class DeepSeekChatService extends BaseChatService{
    private final OkHttpClient client = new OkHttpClient();
    private final List<ChatMessage> chatHistory = new ArrayList<>();

    protected abstract String systemPrompt();

    @Override
    public String chat(String userMessage) throws IOException {
        // 将用户消息添加到对话历史
        chatHistory.add(new ChatMessage("user", userMessage));
        String systemPrompt = systemPrompt();
        if (StringUtils.isNotEmpty(systemPrompt)) {
            chatHistory.add(new ChatMessage("system", systemPrompt));
        }
        // 构建请求体
        JsonObject requestBody = new JsonObject();
        requestBody.addProperty("model", "deepseek-chat"); // 使用 DeepSeek 的聊天模型
        requestBody.addProperty("temperature", 2);
        JsonArray messages = new JsonArray();
        for (ChatMessage message : chatHistory) {
            JsonObject messageJson = new JsonObject();
            messageJson.addProperty("role", message.getRole());
            messageJson.addProperty("content", message.getContent());
            messages.add(messageJson);
        }
        requestBody.add("messages", messages);

        // 构建请求
        Request request = new Request.Builder()
                .url(UrlConstant.DEEP_SEEK_CHAT_API_URL)
                .post(RequestBody.create(requestBody.toString(), MediaType.parse("application/json")))
                .addHeader("Authorization", "Bearer " + UrlConstant.DEEP_SEEK_API_KEY)
                .addHeader("Content-Type", "application/json")
                .build();

        // 发送请求并解析响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败: " + response.code() + " " + response.message());
            }

            String responseBody = response.body().string();
            return parseResponse(responseBody);
        }
    }

    private String parseResponse(String responseBody) {
        JsonObject jsonResponse = JsonParser.parseString(responseBody).getAsJsonObject();
        JsonArray choices = jsonResponse.getAsJsonArray("choices");
        JsonObject firstChoice = choices.get(0).getAsJsonObject();
        String assistantMessage = firstChoice.getAsJsonObject("message").get("content").getAsString();

        // 将助手消息添加到对话历史
        chatHistory.add(new ChatMessage("assistant", assistantMessage));

        return assistantMessage;
    }
}
